package com.demo.filter;

import cn.hutool.core.codec.Base64;
import com.demo.wrapper.MyRequestWrapper;
import com.fasterxml.jackson.core.io.JsonEOFException;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.RequestFacade;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 过滤器，处理GET相关请求
 *
 * @author leo825
 * @date 2022/11/23 17:15
 */
@Slf4j
@Component
@WebFilter(filterName = "decryptGetRequestFilter", urlPatterns = {"/*"})
public class DecryptGetRequestFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        //获取HttpServletRequest对象
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        if ("GET".equalsIgnoreCase(httpServletRequest.getMethod())) {
            String encryKey = httpServletRequest.getHeader("encryKey");
            Map<String, String[]> newParameterMap = new HashMap<>();
            if (StringUtils.isNotBlank(encryKey) && !"MTAw".equalsIgnoreCase(encryKey)) {
                String provinceId = Base64.decodeStr(encryKey);
                log.info("encryKey:{},  provinceId:{}", encryKey, provinceId);
                newParameterMap.put("provinceId", new String[]{provinceId});
            }
            MyRequestWrapper myRequestWrapper = new MyRequestWrapper(httpServletRequest, newParameterMap);
            chain.doFilter(myRequestWrapper, response);
        } else {
            try {
                chain.doFilter(request, response);
            } catch (HttpMessageNotReadableException httpMessageNotReadableException) {
                log.error(((RequestFacade) request).getRequestURI() + ", " + httpMessageNotReadableException.getMessage());
            } catch (JsonEOFException jsonEOFException) {
                log.error(((RequestFacade) request).getRequestURI() + ", " + jsonEOFException.getMessage());
            }
        }
        long end = System.currentTimeMillis();
        log.info("{} 接口耗时：{} ms", httpServletRequest.getRequestURI(), (end-start));
    }

    @Override
    public void destroy() {
    }

}
